package com.kuyu.msg;

import com.kuyu.model.WxFinalValue;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.*;

public class MessageKit {
    private static Map<String,String> replyMsg=new HashMap<>();
    static {
        replyMsg.put("123","你输入了123");
        replyMsg.put("hello","world");
        replyMsg.put("ok","祝你一路ok");
    }
    /**
     * 对xml字符串解析，并将每个节点名称和值存入到map结构中
     * @param req
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static Map<String,String> reqMsg2Map(HttpServletRequest req) throws IOException {
        String xml=req2xmlstr(req);
        try {
            Map<String,String> map=new HashMap<>();
            //解释xml格式，获取节点内容
            Document documente= DocumentHelper.parseText(xml);
            Element root=documente.getRootElement();
            List<Element> eles=root.elements();
            for (Element e:eles){
                map.put(e.getName(),e.getTextTrim());
            }
            return map;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将接收的xml保存到一个字符串中
     * @param req
     * @return
     * @throws IOException
     */
    private static String req2xmlstr(HttpServletRequest req) throws IOException {
        BufferedReader br=null;
        br=new BufferedReader(new InputStreamReader(req.getInputStream()));
        String str=null;
        StringBuilder sb=new StringBuilder();
        while ((str=br.readLine())!=null){
            sb.append(str);
        }
        return sb.toString();
    }

    public static String handlerMeg(Map<String, String> msgMap) throws IOException {
        String msgType=msgMap.get("MsgType");
        if(msgType.equals(WxFinalValue.MSG_TEXT_TYPE)){
            //文本类型
            return textTypehandler(msgMap);
        }
        else if(msgType.equals(WxFinalValue.MSG_EVENT_TYPE)){
            //事件类型
        }
        else if(msgType.equals(WxFinalValue.MSG_IMAGE_TYPE)){
            //文本类型
            return imageTypehandler(msgMap,"OTFynZvNYW2Wy4rEZvFTvg1MKW5R6wJIZeu5V88FzLTsbA_1S4lGWPVGmOouQTjX");
        }
        return null;
    }

    private static String imageTypehandler(Map<String, String> msgMap,String mediaId)throws IOException {
        Map<String,String> map=new HashMap<>();

        map.put("ToUserName",msgMap.get("FromUserName"));
        map.put("FromUserName",msgMap.get("ToUserName"));
        map.put("CreateTime",new Date().getTime()+"");
        map.put("MsgType","image");

        map.put("Image","<MediaId>"+mediaId+"</MediaId>");
        return replyMap2xml(map);
    }

    //处理文本消息回复
    public static String textTypehandler(Map<String, String> msgMap) throws IOException {
        Map<String,String> map=new HashMap<>();

        map.put("ToUserName",msgMap.get("FromUserName"));
        map.put("FromUserName",msgMap.get("ToUserName"));
        map.put("CreateTime",new Date().getTime()+"");
        map.put("MsgType","text");
        String replystr="你发送的消息有误";
        String con=msgMap.get("Content");
        if(replyMsg.containsKey(con)){
            replystr=replyMsg.get(con);
        }
        map.put("Content",replystr);
        return replyMap2xml(map);
    }
    //将回复信息map格式转为xml
    public static String replyMap2xml(Map<String, String> map) throws IOException {
        //创建xml格式，添加节点内容
        Document d=DocumentHelper.createDocument();
        Element root=d.addElement("xml");
        //将map的键，放到一个集合中
        Set<String> keys=map.keySet();
        //变量集合
        for(String key:keys){
            root.addElement(key).addText(map.get(key));
        }
        //将xml写到字符串中，建立一个字符串写入对象
        StringWriter sw=new StringWriter();
        XMLWriter xw=new XMLWriter(sw);
        //设置xml结构中字符不转义
        xw.setEscapeText(false);
        xw.write(d);
        return sw.toString();
    }
}
